<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="edu.zhku.web4.pojo.User" %>
<%@ page import="edu.zhku.web4.util.JdbcUtil" %>
<%@ page import="edu.zhku.web4.common.Constants" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录检验ing</title>
</head>
<body>
<%
    String inputUserName = request.getParameter("username");
    String inputPassword = request.getParameter("pwd");

    User user = null;

    Connection conn = JdbcUtil.getConnection();
    String sql = "SELECT * FROM user WHERE username=?";
    try {
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, inputUserName);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Long userId = rs.getLong("id");
            String username = rs.getString("username");
            String password = rs.getString("password");
            Integer age = rs.getInt("age");

            user = new User(userId, username, password, age);
        }
        rs.close();
        ps.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    if (user != null && inputPassword.equals(user.getPassword())) {
        request.getSession().setAttribute(Constants.USER_SESSION_ID, user);
        response.sendRedirect(request.getContextPath() + "/index.jsp");
    } else {
        request.setAttribute("error", "用户名或密码输入错误！");
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

%>
</body>
</html>
